package com.jinsi.handle;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

// 拦截器
//  拦截所有的请求


@Component
public class LoginHandler implements HandlerInterceptor {

    // 在controller接收请求之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("我被拦截了。。。preHandle。。。。LoginHandle");
        //    return true;

                // true 放行 ,,登录之后
        // false 拦截 ，， 登录之前
        HttpSession session = request.getSession();
        Object user = session.getAttribute("loginuser");
        if(user != null){ // 已经成功登录
            //放行
            return true;
        }else{// 没有登录
            // 去登录页面
            // 重定向到登录页面
            response.sendRedirect("/layuimini/page/login.html");
            return false;


  }

    }

    // 在controller接收请求之后，视图返回前
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        System.out.println("我被拦截了。。。postHandle。。。。LoginHandle");
    }

    // 返回视图之后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("我被拦截了。。。afterCompletion。。。。LoginHandle");

    }
}
